package com.witframework.plugin.jbossrules.support;

import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.log4j.Logger;
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.compiler.PackageBuilder;
import org.drools.rule.Package;
import org.springframework.core.io.Resource;

import com.witframework.plugin.jbossrules.RulesEngineException;


public class DRLRuleBaseLoader extends AbstractFileRuleBaseLoader {
	private static Logger logger = Logger.getLogger(DRLRuleBaseLoader.class);

	public RuleBase buildRuleBase() throws RulesEngineException {
		try {
			Resource[] resources = getRuleFiles(ruleFiles);
			RuleBase ruleBase = RuleBaseFactory.newRuleBase();
			for (int i=0;i< resources.length;i++) {
					// read in the source
					Reader source = new InputStreamReader(resources[i].getInputStream(),"UTF-8");
					PackageBuilder builder = new PackageBuilder();
					//the one argument one is for normal DRL.
					builder.addPackageFromDrl(source);
					// get the compiled package (which is serializable)
					Package pkg = builder.getPackage();
					// add the package to a rulebase (deploy the rule package).
					ruleBase.addPackage(pkg);
					source.close();
			}
			return ruleBase;
		} catch (Exception e) {
			logger.error("Exception occurred while load rules.",e);
			throw new RulesEngineException("Could not load rules", e);
		}
	}
}
